package com.tsugun.mediaplayer.view.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.tsugun.mediaplayer.R;

/**
 * 触摸开关按钮
 * Created by shize on 2017/5/31.
 * example:
 * <com.tsugun.mediaplayer.view.widget.TouchActionButton
 * android:id="@+id/id_touch_button"
 * android:layout_width="48dp"
 * android:layout_height="24dp"
 * android:layout_below="@id/id_toolbar_layout"
 * android:layout_centerHorizontal="true"
 * app:buttonLayout="@layout/layout_touch_button"
 * app:closeBackground="@drawable/bg_action_button_grey"
 * app:openBackground="@drawable/bg_action_button_blue"
 * app:status="false" />
 */

public class TouchActionButton extends RelativeLayout implements View.OnTouchListener,
        GestureDetector.OnGestureListener {

    private int mButtonId;
    private boolean isOpen;
    private View mButtonView;
    private View mBgView;
    private LayoutInflater mInflater;
    private GestureDetector mGDetector;

    private int tfDip; // 开关间距
    private int startDip; // 前后间距
    private int topDip; // 上下间距
    private Drawable open;
    private Drawable close;
    private int paddingLeft;
    private int paddingRight;
    private boolean isClick; // 是否为点击

    public TouchActionButton(Context context) {
        this(context, null);
    }

    public TouchActionButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TouchActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TouchActionButton,
                defStyleAttr, 0);
        mButtonId = a.getResourceId(R.styleable.TouchActionButton_buttonLayout, R.layout.layout_touch_button);
        isOpen = a.getBoolean(R.styleable.TouchActionButton_status, false);
        open = a.getDrawable(R.styleable.TouchActionButton_openBackground);
        close = a.getDrawable(R.styleable.TouchActionButton_closeBackground);
        a.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mInflater = LayoutInflater.from(getContext());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        showButton();
        mGDetector = new GestureDetector(getContext(), this);
        setOnTouchListener(this);
        startDip = mButtonView.getPaddingStart();
        topDip = mButtonView.getPaddingTop();
        tfDip = w / 2 + startDip;
        Log.e("ss", "initData: " + tfDip);
        changeStatus(isOpen);
    }

    private void showButton() {
        if (mButtonView == null) {
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            // 背景遮罩
            mBgView = new View(getContext());
            addView(mBgView, 0, lp);
            mBgView.setBackground(open);
            // button本体
            mButtonView = mInflater.inflate(mButtonId, null);
            addView(mButtonView, 1, lp);
            setBackground(close);
        }
    }

    private void changeStatus(boolean status) {
        isOpen = status;
        if (isOpen) {
            mBgView.setAlpha(1);
            mButtonView.setPadding(tfDip, topDip, startDip, topDip);
        } else {
            mBgView.setAlpha(0);
            mButtonView.setPadding(startDip, topDip, tfDip, topDip);
        }
    }

    /**
     * 设置动画
     *
     * @param now    当前值
     * @param target 目标值
     */
    private void doAnimation(int now, int target) {
        ValueAnimator animation = ValueAnimator.ofInt(now, target);
        animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = (Integer) animation.getAnimatedValue();
                if (isOpen) {
                    setPaddingLeft(value);
                } else {
                    setPaddingRight(value);
                }
            }
        });
        animation.setDuration(160);
        animation.start();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 阻止所有父容器拦截
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mGDetector.onTouchEvent(event);
        // 在结束滑动后判断开关状态
        if (event.getAction() == MotionEvent.ACTION_UP ||
                event.getAction() == MotionEvent.ACTION_CANCEL) {
            if (isClick) {
                setStatus(!isOpen);
                // 点击启动动画
                doAnimation(startDip, tfDip);
            } else {
                setStatus(paddingLeft > paddingRight);
                // 点击启动动画
                if (paddingLeft != startDip) {
                    doAnimation(paddingLeft, tfDip);
                } else {
                    doAnimation(paddingRight, tfDip);
                }
            }
        }
        Log.e("ss", "onTouch: " + event.getAction());
        return true;
    }

    /**
     * 设置开关状态
     *
     * @param status boolean
     */
    public void setStatus(boolean status) {
        changeStatus(status);
    }

    public boolean isOpen() {
        return isOpen;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        isClick = true;
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        isClick = false;
        paddingLeft = mButtonView.getPaddingLeft();
        paddingRight = mButtonView.getPaddingRight();
        setBgViewAlpha();
        if (distanceX > 0) {
            // 向左滑动
            setPaddingLeft((int) (paddingLeft - distanceX));
        } else {
            // 向右滑动
            setPaddingRight((int) (paddingRight - Math.abs(distanceX)));
        }
        return true;
    }

    /**
     * 设置左padding
     */
    private void setPaddingLeft(int padding) {
        if (padding > tfDip) {
            mButtonView.setPadding(tfDip, topDip, startDip, topDip);
        } else if (padding < startDip) {
            setPaddingRight(paddingRight + startDip - padding);
        } else {
            mButtonView.setPadding(padding, topDip, startDip, topDip);
        }
    }

    /**
     * 设置右padding
     */
    private void setPaddingRight(int padding) {
        if (padding > tfDip) {
            mButtonView.setPadding(startDip, topDip, tfDip, topDip);
        } else if (padding < startDip) {
            setPaddingLeft(paddingLeft + startDip - padding);
        } else {
            mButtonView.setPadding(startDip, topDip, padding, topDip);
        }
    }

    /**
     * 设置背景色
     */
    private void setBgViewAlpha() {
        float alpha;
        int padding = tfDip - startDip;
        double total = padding * 2.0;
        if (paddingLeft > startDip) {
            alpha = (float) ((paddingLeft - startDip + padding) / total);
        } else {
            alpha = (float) ((padding - (paddingRight - startDip)) / total);
        }
        mBgView.setAlpha(alpha);
    }

    @Override
    public void onLongPress(MotionEvent e) {
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return true;
    }
}
